#include "homewindow.h"
#include "ui_homewindow.h"
#include <QDebug>
//#include "../tcp/basetcp.h"

#include "setting.h"
#include "staticstrenthtestform.h"
#include "durabilitytestform.h"
#include "actiondebugform.h"
#include "njtestreportform.h"
#include "testcurveform.h"
#include "netmanager.h"

#include "form/formmanager.h"
#include "config/constants.h"
#include "config/config.h"
#include <util/utils.h>

HomeWindow::HomeWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::HomeWindow)
{
    isRunning = false;
    ui->setupUi(this);
    initWindow();
    initResource();
}

HomeWindow::~HomeWindow()
{
    delete ui;
}

void HomeWindow::readConfig()
{
    /// 读取配置文件。
    Config cfg;
    QVariant val = cfg.Get(TEST_PARAM_NAME, TEST_PARAM_SELECT);
    if(val.isValid())
    {
        auto tempValue = val.toBool();
        if(tempValue)
        {
            ui->rbMainStaticTest->setChecked(Qt::Checked);
            ui->rbMainDynamicTest->setChecked(Qt::Unchecked);
        }
        else
        {
            ui->rbMainStaticTest->setChecked(Qt::Unchecked);
            ui->rbMainDynamicTest->setChecked(Qt::Checked);
        }
        paramModel.ctrlMethod = tempValue;

        val = cfg.Get(TEST_PARAM_NAME, TEST_PARAM_CTRL_STYLE);
        tempValue = val.toBool();
        if(tempValue)
        {
            ui->rbMainLoadCtrl->setChecked(Qt::Checked);
            ui->rbMainDisplamentCtrl->setChecked(Qt::Unchecked);
        }
        else
        {
            ui->rbMainLoadCtrl->setChecked(Qt::Unchecked);
            ui->rbMainDisplamentCtrl->setChecked(Qt::Checked);
        }
        paramModel.testMethod = tempValue;

        val = cfg.Get(TEST_PARAM_NAME, TEST_PARAM_SPEED);
        ui->leMainLoadSpeed->setText(QString::number(val.toInt()));
        paramModel.testSpeed = val.toInt();

        val = cfg.Get(TEST_PARAM_NAME, TEST_PARAM_PRELOAD);
        tempValue = val.toFloat();
        ui->leMainPreLoad->setText(Utils::formatFloat(val.toFloat()));
        paramModel.preLoad = val.toFloat();

        val = cfg.Get(TEST_PARAM_NAME, TEST_PARAM_LOAD);
        tempValue = val.toFloat();
        ui->leMainLoad->setText(Utils::formatFloat(val.toFloat()));
        paramModel.load = val.toFloat();

        val = cfg.Get(TEST_PARAM_NAME, TEST_PARAM_NUM);
        tempValue = val.toInt();
        ui->leMainDefineNum->setText(QString::number(val.toInt()));
        paramModel.testNum = val.toInt();

        val = cfg.Get(TEST_PARAM_NAME, TEST_PARAM_KEEP_TIME);
        tempValue = val.toInt();
        ui->leMainKeepTime->setText(QString::number(val.toInt()));
        paramModel.keepTime = val.toInt();

        val = cfg.Get(TEST_PARAM_NAME, TEST_PARAM_UP);
        tempValue = val.toInt();
        ui->leMainMinDistance->setText(QString::number(val.toInt()));
        paramModel.upVal = val.toInt();

        val = cfg.Get(TEST_PARAM_NAME, TEST_PARAM_DOWN);
        tempValue = val.toInt();
        ui->leMainMaxDisplament->setText(QString::number(val.toInt()));
        paramModel.downVal = val.toInt();


    }

}

void HomeWindow::startRunningTest()
{
    displacementChart->resetAxis();
}

void HomeWindow::stopRunningTest()
{

}

void HomeWindow::on_receive_handle_data(QByteArray ba)
{
//    ui->lbTest->setText("12");
//    qDebug()<< "刷新UI线程";
}

///
/// \brief HomeWindow::onReceiveResult
/// \param realDataModel
/// 接收控制器发送的实时数据。
void HomeWindow::onReceiveResult(RealDataModel realDataModel)
{
    tcpDataModel = realDataModel;
}

///参数设置
void HomeWindow::on_menuSetting_triggered()
{
    formManager->settingForm->show();
}

/// 静强度试验微调
void HomeWindow::on_menuStaticFineDebug_triggered()
{
    formManager->staticStrenthTestForm->show();
}

void HomeWindow::on_menuLongFineDebug_triggered()
{
    formManager->durTestForm->show();
}

void HomeWindow::on_menuActionDebug_triggered()
{
    formManager->acionForm->show();
}

void HomeWindow::on_menuLongReport_triggered()
{
    formManager->njTestReportForm->show();
}

void HomeWindow::on_menuStaticCurve_triggered()
{
    formManager->testCurveForm->show();
}

void HomeWindow::on_menuNetConnect_triggered()
{
    formManager->netManager->show();
}

void HomeWindow::onDisplacementChart()
{
    if(formManager->acionForm->isRunDebug() || isRunning && ui->rbMainDisplamentCtrl->isChecked())
    {
        displacementChart->updateChart(tcpDataModel.analogVec[0]);
    }

}

void HomeWindow::flushNetStatus(const QString& status)
{
    netStatusLabel->setText(status);
}

void HomeWindow::initWindow()
{
    ui->rbMainStaticTest->setEnabled(false);
    ui->rbMainLoadCtrl->setEnabled(false);
    ui->rbMainDynamicTest->setEnabled(false);
    ui->rbMainDisplamentCtrl->setEnabled(false);

    netStatusLabel = new QLabel(this);
    netStatusLabel->setFrameShape(QFrame::WinPanel);
    netStatusLabel->setFrameShadow(QFrame::Sunken);
    netStatusLabel->setText("控制器:未连接！");
    netStatusLabel->setFixedWidth(200);
    netStatusLabel->setStyleSheet("font: bold; font-size:20px; color: rgb(241, 70, 62); background-color: rgb(255, 250, 205)");
    ui->mainStatusBar->addWidget(netStatusLabel);

//    QAction* settingAction  = new QAction(tr("参数设定"), this);

//    ui->menubar->insertAction(ui->menuNetConnect, settingAction);
    ui->menubar->addAction(ui->menuNetConnect);
    ui->menubar->addAction(ui->menuSetting);

    QMenu* menuTestDataAnalysis = new QMenu("试验数据分析");
    menuTestDataAnalysis->addAction(ui->menuReport);
    menuTestDataAnalysis->addAction(ui->menuStaticCurve);
    menuTestDataAnalysis->addAction(ui->menuLongReport);
    ui->menubar->addMenu(menuTestDataAnalysis);

    QMenu* menuDebug = new QMenu("调试");
    menuDebug->addAction(ui->menuActionDebug);
    QMenu* menuPrecisionFineTurning = new QMenu("精度微调");
    menuPrecisionFineTurning->addAction(ui->menuLongFineDebug);
    menuPrecisionFineTurning->addAction(ui->menuStaticFineDebug);
    menuDebug->addMenu(menuPrecisionFineTurning);
    ui->menubar->addMenu(menuDebug);

    readConfig();
    displacementTimer = new QTimer(this);
    displacementTimer->setTimerType(Qt::PreciseTimer);

    connect(displacementTimer, SIGNAL(timeout()), this, SLOT(onDisplacementChart()));

    displacementTimer->start(100);
}

void HomeWindow::initResource()
{
    loadDisplaceChart = QSharedPointer<LoadDisplacementChart>(new LoadDisplacementChart(ui->mainLoadDisplacementChart));
    displacementChart = QSharedPointer<DisplacementChart>(new DisplacementChart(ui->mainDisplacementChart));
    loadChart = QSharedPointer<LoadChart>(new LoadChart(ui->mainLoadChart));
    adpterManager = QSharedPointer<AdpterManager>(new AdpterManager(this));
    formManager = QSharedPointer<FormManager>(new FormManager());
    formManager->settingForm->setUpdateMainCallback(std::bind(&HomeWindow::readConfig, this));
    formManager->acionForm->setHomeWindowPtr(this);

    connectManager = new ConnectManager(this, formManager, adpterManager);
}

void HomeWindow::on_btnMainStart_clicked()
{
    displacementChart->resetAxis();

    connectManager->sendCommand(Utils::formatCommand("SET", 0.0));
    Utils::delay(1);
    float up = paramModel.upVal;
    float down = paramModel.downVal;
    float res = fabs(up - down) / 2;
    connectManager->sendCommand(Utils::formatCommand("ZZF", res));
    Utils::delay(1);
    connectManager->sendCommand(Utils::formatCommand("MAX", up));
    Utils::delay(1);
    float freq = paramModel.testFreq;
    connectManager->sendCommand(Utils::formatCommand("ZPL", freq));

    float num = paramModel.testNum;
    connectManager->sendCommand(Utils::formatCommand("NUM", num));
    Utils::delay(1);

    float stSpeed = paramModel.testSpeed;
    stSpeed = stSpeed/up;
    stSpeed = stSpeed/freq;
    connectManager->sendCommand(Utils::formatCommand("D_V", stSpeed));
    Utils::delay(1);

    ///默认正玄波
    /// 需要添加三角波
    connectManager->sendCommand("{BFS[Z]}");
    Utils::delay(1);

    if(!paramModel.ctrlMethod)
    {
        connectManager->sendCommand("{TRE[W]}");
    }
    else
    {
        connectManager->sendCommand("{TRE[L]}");
    }
    isRunning = true;
}

void HomeWindow::on_btnMainStop_clicked()
{
    QString cmd = "{SCH[W]}";
    connectManager->sendCommand(cmd);
    Utils::delay(10);
    cmd = "{RUN[T]}";
    connectManager->sendCommand(cmd);
    isRunning = false;
}

void HomeWindow::on_btnMainServoStart_clicked()
{
    /// 伺服启动
    QString cmd = "{CE1[Y]}";
    connectManager->sendCommand(cmd);
    isRunning = true;

    ui->btnMainServoStop->setEnabled(true);
    ui->btnMainServoStart->setEnabled(false);
}

void HomeWindow::on_btnMainServoStop_clicked()
{   
    /// 伺服关闭
    QString cmd = "{CE1[N]}";
    connectManager->sendCommand(cmd);
    isRunning = false;

    ui->btnMainServoStop->setEnabled(false);
    ui->btnMainServoStart->setEnabled(true);
}

void HomeWindow::on_menu_test()
{
    LOG_INFO << "This is a Test ==================";
}
